package spindles.api.db;

import spindles.api.util.ApplicationException;

import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Transaction;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityIndex;


public abstract class Closeable<V> {
	
	private EntityCursor<V> cursor;
	
	private Transaction txn;
	
	
	public Closeable(EntityCursor<V> cursor) {		
		this.cursor = cursor;		
	}
	
	
	
	public Closeable(EntityIndex<Long, V> entityIndex){		
		txn = DB.beginTransaction();
		try {
			cursor = entityIndex.entities(txn, DB.getCursorConfig());
		} catch (DatabaseException e) {
			throw new ApplicationException(e);
		}
	}

	public abstract void execute(EntityCursor<V> cursor) throws DatabaseException;

	public void run() {
		try {
			execute(cursor);
			cursor.close();
		} catch (DatabaseException e) {
			throw new ApplicationException(e);
		}
	}
	
	public void runTxn(){		
		try {
			execute(cursor);
			
			cursor.close();
			cursor = null;
			
			txn.commit();
			txn = null;			
		} catch (DatabaseException e) {
			DB.close(cursor);
			DB.abort(txn);
			throw new ApplicationException(e);
		}
	}
}
